package com.dianrui.operation.okhttp;

import android.os.Handler;
import android.os.Looper;

import com.blankj.utilcode.util.LogUtils;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;

public class OkHttpRequest {
    private Handler handler;
    private volatile static OkHttpRequest mInstance;
    private OkHttpClient mOkHttpClient;

    public OkHttpRequest(OkHttpClient okHttpClient) {
        handler = new Handler(Looper.getMainLooper());
        if (okHttpClient == null) {
            mOkHttpClient = new OkHttpClient();
        } else {
            mOkHttpClient = okHttpClient;
        }
    }


    /**
     * 单例模式
     */
    //获取单利
    public static OkHttpRequest getInstance() {

        return initClient(null);

    }

    public static OkHttpRequest initClient(OkHttpClient okHttpClient) {
        if (mInstance == null) {
            synchronized (OkHttpRequest.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpRequest(okHttpClient);
                }
            }
        }
        return mInstance;
    }


    public void postRequests(final String url, final String requestparams, final XCallBack callback) {
        String token = SharedUtil.getToken();
        LogUtils.e("当前token是"+token);
        OkHttpUtils.postString().url(url).content(requestparams).addHeader("token", token).mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                LogUtils.e("请求失败=" + e.getMessage());
                onFailedResponse(call.toString(), callback);
                call.cancel();
            }

            @Override
            public void onResponse(String response, int id) {
                if (!StringUtils.isEmpty(response)) {
                    onSuccessResponse(response, callback);
                   LogUtils.e("====================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n传给服务器的参数:" + requestparams +
                            "\n\n服务器返回的数据>" + response);
                }else {
                    LogUtils.e("服务器返回数据>==========================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n服务器返回的数据>" + response);
                    onFailedResponse(response, callback);
                }
            }
        });
    }

    public void postRequest(final String url, final String requestparams, final XCallBack callback) {
        OkHttpUtils.postString().url(url).content(requestparams).mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                LogUtils.e("请求失败=" + e.getMessage());
                onFailedResponse(e.getMessage(), callback);
                call.cancel();
            }

            @Override
            public void onResponse(String response, int id) {
                if (!StringUtils.isEmpty(response)) {
                    onSuccessResponse(response, callback);
                    LogUtils.e("服务器返回数据>============================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n传给服务器的参数:" + requestparams +
                            "\n\n服务器返回的数据>" + response);
                }else {
                    LogUtils.e("服务器返回数据>===========================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n服务器返回的数据>" + response);
                    onFailedResponse(response, callback);
                }
            }
        });
    }


    //Get请求
    public void getRequest(final String url,final XCallBack callback) {
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                LogUtils.e("请求失败=" + e.getMessage());
                onFailedResponse(call.toString(), callback);
                call.cancel();
            }

            @Override
            public void onResponse(String response, int id) {
                if (!StringUtils.isEmpty(response)) {
                    onSuccessResponse(response, callback);
                    LogUtils.e("服务器返回数据>================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n服务器返回的数据>" + response);
                }else {
                    LogUtils.e("服务器返回数据>================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n服务器返回的数据>" + response);
                    onFailedResponse(response, callback);
                }
            }
        });
    }


    private void onSuccessResponse(final String result, final XCallBack callBack) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    callBack.onResponse(result);
                }
            }
        });
    }

    private void onFailedResponse(final String result, final XCallBack callBack) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    callBack.failedRequest(result);
                }
            }
        });
    }


    public interface XCallBack {
        void onResponse(String result);
        void failedRequest(String result);
    }
}
